package com.generic;

import java.util.ArrayList;

/**
 * @author LingLed
 * @version 1.0
 */
public class Generic01 {
    public static void main(String[] args) {
        //泛型引出

        ArrayList arrayList = new ArrayList();
        arrayList.add(new Dog("yu", 20));
        arrayList.add(new Dog("zhang", 20));
        //arrayList.add(new Cat("zhang", 20));
        //正常写一个集合的遍历需要向下转型,但如果这个集合元素不是统一的类型
        //则这样会报错
        //这个时候就需要泛型去限制这个集合的类型,同样也可以省去向下转型,来提高效率
        for (Object o : arrayList) {
            Dog dog = (Dog) o;
            System.out.println(dog.name + "-" + dog.age);
        }

        ArrayList<Dog> arrayList1 = new ArrayList<Dog>();
        arrayList1.add(new Dog("yu", 20));
        arrayList1.add(new Dog("zhang", 20));
        //arrayList1.add(new Cat("zhang", 20));
        //正常写一个集合的遍历需要向下转型,但如果这个集合元素不是统一的类型
        //则这样会报错
        //这个时候就需要泛型去限制这个集合的类型,同样也可以省去向下转型,来提高效率
        for (Dog dog : arrayList1) {
            System.out.println(dog.name + "-" + dog.age);
        }

    }

    static class Dog {
        String name;
        int age;

        public Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }

    }

    static class Cat {
        String name;
        int age;

        public Cat(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}


